package me.qingy.shiro.service;

import me.qingy.core.entity.User;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.stereotype.Component;

import java.io.UTFDataFormatException;

/**
 * @author qingy
 * @since 2021-05-07
 */
@Component
public class PasswordService {

    public void validate(User user, String password) {
        if (!matches(user, password)){
            throw new AuthenticationException("密码错误");
        }
    }

    public boolean matches(User user, String newPassword) {
        return user.getPassword().equals(encryptPassword(user.getLoginName(), newPassword, user.getSalt()));
    }

    public String encryptPassword(String loginName, String password, String salt) {
        return new Md5Hash(loginName + password + salt).toHex();
    }

}
